package br.uff.pgci.sgca.gateway.server;

import br.uff.pgci.sgca.gateway.codec.MensagemDecoder;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.bootstrap.ConnectionlessBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.FixedReceiveBufferSizePredictorFactory;
import org.jboss.netty.channel.socket.DatagramChannelFactory;
import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;
import org.jboss.netty.handler.logging.LoggingHandler;
import org.jboss.netty.logging.InternalLogLevel;
import org.jboss.netty.util.CharsetUtil;

/**
 * Servidor UDP do Gateway SGCA
 */
public class ServidorUDP {

    private static final Logger logger = Logger.getLogger(ServidorUDP.class.getName());
    public static int PORTA_SERVIDOR_UDP = 9090;
    DatagramChannelFactory fabrica;
    ConnectionlessBootstrap bootstrap;
    Channel canal;

    public ServidorUDP() {
    }

    public void iniciarServidorUDP() {
        fabrica = new NioDatagramChannelFactory(Executors.newCachedThreadPool());
        //Pode ser OioDatagramChannelFactory => Ver qual a diferenca

        bootstrap = new ConnectionlessBootstrap(fabrica);

        // Configure the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {

            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
//                pipeline.addLast("logginHandler", new LoggingHandler(InternalLogLevel.ERROR));
                pipeline.addLast("decoderDeString", new StringDecoder(CharsetUtil.ISO_8859_1));
                pipeline.addLast("decoderDeMensagem", new MensagemDecoder());
                pipeline.addLast("handlerGerente", new Gerente());
                pipeline.addLast("encoderDeString", new StringEncoder(CharsetUtil.ISO_8859_1));
                return pipeline;
            }
        });

        // Enable broadcast
        bootstrap.setOption("broadcast", "false");

        // Allow packets as large as up to 1024 bytes (default is 768).
        // You could increase or decrease this value to avoid truncated packets
        // or to improve memory footprint respectively.
        //
        // Please also note that a large UDP packet might be truncated or
        // dropped by your router no matter how you configured this option.
        // In UDP, a packet is truncated or dropped if it is larger than a
        // certain size, depending on router configuration.  IPv4 routers
        // truncate and IPv6 routers drop a large packet.  That's why it is
        // safe to send small packets in UDP.
        bootstrap.setOption(
                "receiveBufferSizePredictorFactory",
                new FixedReceiveBufferSizePredictorFactory(1024));

        bootstrap.setOption("receiveBufferSize", 65536);
        bootstrap.setOption("sendBufferSize", 65536);

//        logger.log(Level.INFO, "Subindo o Servidor UDP na porta: {0}", ServidorUDP.PORTA_SERVIDOR_UDP);
        // Bind na porta especifica e iniciando o servico
        canal = bootstrap.bind(new InetSocketAddress(ServidorUDP.PORTA_SERVIDOR_UDP));

//        logger.log(Level.INFO, "Servidor UDP do Gateway SGCA iniciado com sucesso, aguardando requisicoes...");

    }

    void finalizarServidorUDP() {
        logger.log(Level.INFO, "Finalizando o Servidor UDP da porta: {0}", ServidorUDP.PORTA_SERVIDOR_UDP);
        canal.disconnect().awaitUninterruptibly();
        canal.close().awaitUninterruptibly();
        canal.unbind().awaitUninterruptibly();

        bootstrap.releaseExternalResources();

        fabrica.releaseExternalResources();
        logger.log(Level.INFO, "Servidor UDP finalizado com sucesso");
    }
}
